package com.yanqu.road.server.manger.statistics;

import com.yanqu.road.entity.statistics.AbilityStatistics;
import com.yanqu.road.logic.bussiness.player.UserHistoryAttributeBussiness;
import com.yanqu.road.logic.bussiness.statistics.StatisticsBusiness;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.utils.LocalDateTimeHelper;
import com.yanqu.road.utils.date.DateHelper;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 统计数据
 */
public class StatisticsMgr extends TempMgr {

    private static long serverId = GameServer.getInstance().getServerId();

    // Map<0点时间，数据>
    private static Map<Long, AbilityStatistics> abilityStatisticsMap = new ConcurrentHashMap<>();

    @Override
    public boolean reloadData() throws Exception {
        // 获取最近十天内的数据
        long startTime = LocalDateTimeHelper.getZeroTimeTimeStamp(System.currentTimeMillis() - 10 * DateHelper.DAY_MILLIONS);
        serverId = GameServer.getInstance().getServerId();
        abilityStatisticsMap = StatisticsBusiness.getAbilityStatisticsMap(serverId, startTime);
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean save() {
        for (AbilityStatistics value : abilityStatisticsMap.values()) {
            if (value.isInsertOption()) {
                StatisticsBusiness.addAbilityStatistics(value);
            } else if (value.isUpdateOption()) {
                StatisticsBusiness.updateAbilityStatistics(value);
            }
        }
        return true;
    }

    /**
     * 统计区服门客总赚钱数据
     */
    public static void doAbilityStatistics() {

        long zeroTimeTimeStamp = LocalDateTimeHelper.getZeroTimeTimeStamp();

        AbilityStatistics abilityStatistics = new AbilityStatistics();
        abilityStatistics.setServerId(serverId);
        abilityStatistics.setZeroTime(zeroTimeTimeStamp);
        abilityStatistics.setAbility(UserHistoryAttributeBussiness.getAllHistoryByLoginUser(zeroTimeTimeStamp / 1000));

        synchronized (abilityStatisticsMap) {
            if (!abilityStatisticsMap.containsKey(abilityStatistics.getZeroTime())) {
                abilityStatistics.setInsertOption();
            } else {
                abilityStatistics.setUpdateOption();
            }
            abilityStatisticsMap.put(abilityStatistics.getZeroTime(), abilityStatistics);
        }
    }

    public static Map<Long, AbilityStatistics> getAbilityStatisticsMap() {
        return abilityStatisticsMap;
    }
}
